<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>

	
		<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
		<meta http-equiv="Content-Language" content="en-us">

		<title>Django | How to use sessions | Django Documentation</title>

		<meta name="ROBOTS" content="ALL">
		<meta http-equiv="imagetoolbar" content="no">
		<meta name="MSSmartTagsPreventParsing" content="true">
		<meta name="Copyright" content="This site's design and contents Copyright (c) 2005  Lawrence Journal-World.">

		<meta name="keywords" content="Python, Django, framework, open-source">
		<meta name="description" content="Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.">

		<link href="Django%20%7C%20How%20to%20use%20sessions%20%7C%20Django%20Documentation_files/base.css" rel="stylesheet" type="text/css" media="screen">
		<link href="Django%20%7C%20How%20to%20use%20sessions%20%7C%20Django%20Documentation_files/print.css" rel="stylesheet" type="text/css" media="print">
      
  
  <style type="text/css" media="screen">
    #docs-search {
      color: #000;
      float: right;
    }
    #docs-search form {
      font-size: 92%;
      margin: 0;
      padding: 1em 1em 0;
      white-space: nowrap;
    }
    form.search ul {
      list-style: none;
      margin: 0;
      padding: 0;
    }
    form.search li {
      display: inline;
      padding-right: 1em;
    }
    form.search .query {
      width: 18em;
    }
  </style>
  <link rel="stylesheet" href="Django%20%7C%20How%20to%20use%20sessions%20%7C%20Django%20Documentation_files/pygments.css" type="text/css">

	</head><body id="documentation" class="default">

	<div id="container">
		<div id="header">
			<h1 id="logo"><a href="http://www.djangoproject.com/"><img src="Django%20%7C%20How%20to%20use%20sessions%20%7C%20Django%20Documentation_files/hdr_logo.gif" alt="Django"></a></h1>
			<ul id="nav-global">
				<li id="nav-homepage"><a href="http://www.djangoproject.com/">Home</a></li>
				<li id="nav-download"><a href="http://www.djangoproject.com/download/">Download</a></li>
				<li id="nav-documentation"><a href="http://docs.djangoproject.com/">Documentation</a></li>
				<li id="nav-weblog"><a href="http://www.djangoproject.com/weblog/">Weblog</a></li>
				<li id="nav-community"><a href="http://www.djangoproject.com/community/">Community</a></li>
				<li id="nav-code"><a href="http://code.djangoproject.com/">Code</a></li>
			</ul>
		</div>
		<!-- END Header -->
		<div id="billboard">
  <h2><a href="http://docs.djangoproject.com/en/1.0/">Django documentation</a></h2>
</div>
		<div id="columnwrap">
			
		<div id="content-main">
		


  <h2 class="deck">
  
    This document describes Django version 1.0. For development documentation, 
    <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/">go here</a>.
  
  </h2>
  <div class="section" id="s-how-to-use-sessions">
<span id="s-topics-http-sessions"></span><span id="how-to-use-sessions"></span><span id="topics-http-sessions"></span><h1>How to use sessions<a class="headerlink" href="#how-to-use-sessions" title="Permalink to this headline">¶</a></h1>
<p>Django provides full support for anonymous sessions. The session framework lets
you store and retrieve arbitrary data on a per-site-visitor basis. It stores
data on the server side and abstracts the sending and receiving of cookies.
Cookies contain a session ID – not the data itself.</p>
<div class="section" id="s-enabling-sessions">
<span id="enabling-sessions"></span><h2>Enabling sessions<a class="headerlink" href="#enabling-sessions" title="Permalink to this headline">¶</a></h2>
<p>Sessions are implemented via a piece of <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/middleware/#ref-middleware"><em>middleware</em></a>.</p>
<p>To enable session functionality, do the following:</p>
<ul class="simple">
<li>Edit the <tt class="docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></tt> setting and make sure
<tt class="docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></tt> contains <tt class="docutils literal"><span class="pre">'django.contrib.sessions.middleware.SessionMiddleware'</span></tt>.
The default <tt class="docutils literal"><span class="pre">settings.py</span></tt> created by <tt class="docutils literal"><span class="pre">django-admin.py</span> <span class="pre">startproject</span></tt> has
<tt class="docutils literal"><span class="pre">SessionMiddleware</span></tt> activated.</li>
<li>Add <tt class="docutils literal"><span class="pre">'django.contrib.sessions'</span></tt> to your <tt class="docutils literal"><span class="pre">INSTALLED_APPS</span></tt> setting,
and run <tt class="docutils literal"><span class="pre">manage.py</span> <span class="pre">syncdb</span></tt> to install the single database table
that stores session data.</li>
</ul>
<div class="versionchanged">
<span class="title">Changed in Django 1.0:</span> This step is optional if you’re not using the database session backend;
see <a class="reference internal" href="#configuring-the-session-engine">configuring the session engine</a>.</div>
<p>If you don’t want to use sessions, you might as well remove the
<tt class="docutils literal"><span class="pre">SessionMiddleware</span></tt> line from <tt class="docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></tt> and <tt class="docutils literal"><span class="pre">'django.contrib.sessions'</span></tt>
from your <tt class="docutils literal"><span class="pre">INSTALLED_APPS</span></tt>. It’ll save you a small bit of overhead.</p>
</div>
<div class="section" id="s-configuring-the-session-engine">
<span id="configuring-the-session-engine"></span><h2>Configuring the session engine<a class="headerlink" href="#configuring-the-session-engine" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>By default, Django stores sessions in your database (using the model
<tt class="docutils literal"><span class="pre">django.contrib.sessions.models.Session</span></tt>). Though this is convenient, in
some setups it’s faster to store session data elsewhere, so Django can be
configured to store session data on your filesystem or in your cache.</p>
<div class="section" id="s-using-file-based-sessions">
<span id="using-file-based-sessions"></span><h3>Using file-based sessions<a class="headerlink" href="#using-file-based-sessions" title="Permalink to this headline">¶</a></h3>
<p>To use file-based sessions, set the <tt class="docutils literal"><span class="pre">SESSION_ENGINE</span></tt> setting to
<tt class="docutils literal"><span class="pre">"django.contrib.sessions.backends.file"</span></tt>.</p>
<p>You might also want to set the <tt class="docutils literal"><span class="pre">SESSION_FILE_PATH</span></tt> setting (which defaults
to output from <tt class="docutils literal"><span class="pre">tempfile.gettempdir()</span></tt>, most likely <tt class="docutils literal"><span class="pre">/tmp</span></tt>) to control
where Django stores session files. Be sure to check that your Web server has
permissions to read and write to this location.</p>
</div>
<div class="section" id="s-using-cache-based-sessions">
<span id="using-cache-based-sessions"></span><h3>Using cache-based sessions<a class="headerlink" href="#using-cache-based-sessions" title="Permalink to this headline">¶</a></h3>
<p>To store session data using Django’s cache system, set <tt class="docutils literal"><span class="pre">SESSION_ENGINE</span></tt>
to <tt class="docutils literal"><span class="pre">"django.contrib.sessions.backends.cache"</span></tt>. You’ll want to make sure
you’ve configured your cache; see the <a class="reference external" href="http://docs.djangoproject.com/en/1.0/topics/cache/#topics-cache"><em>cache documentation</em></a> for details.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">You should probably only use cache-based sessions if you’re using the
Memcached cache backend. The local-memory cache backend doesn’t retain data
long enough to be a good choice, and it’ll be faster to use file or
database sessions directly instead of sending everything through the file
or database cache backends.</p>
</div>
</div>
</div>
<div class="section" id="s-using-sessions-in-views">
<span id="using-sessions-in-views"></span><h2>Using sessions in views<a class="headerlink" href="#using-sessions-in-views" title="Permalink to this headline">¶</a></h2>
<p>When <tt class="docutils literal"><span class="pre">SessionMiddleware</span></tt> is activated, each <tt class="docutils literal"><span class="pre">HttpRequest</span></tt> object – the
first argument to any Django view function – will have a <tt class="docutils literal"><span class="pre">session</span></tt>
attribute, which is a dictionary-like object. You can read it and write to it.</p>
<p>A session object has the following standard dictionary methods:</p>
<ul>
<li><p class="first"><tt class="docutils literal"><span class="pre">__getitem__(key)</span></tt></p>
<p>Example: <tt class="docutils literal"><span class="pre">fav_color</span> <span class="pre">=</span> <span class="pre">request.session['fav_color']</span></tt></p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">__setitem__(key,</span> <span class="pre">value)</span></tt></p>
<p>Example: <tt class="docutils literal"><span class="pre">request.session['fav_color']</span> <span class="pre">=</span> <span class="pre">'blue'</span></tt></p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">__delitem__(key)</span></tt></p>
<p>Example: <tt class="docutils literal"><span class="pre">del</span> <span class="pre">request.session['fav_color']</span></tt>. This raises <tt class="docutils literal"><span class="pre">KeyError</span></tt>
if the given <tt class="docutils literal"><span class="pre">key</span></tt> isn’t already in the session.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">__contains__(key)</span></tt></p>
<p>Example: <tt class="docutils literal"><span class="pre">'fav_color'</span> <span class="pre">in</span> <span class="pre">request.session</span></tt></p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">get(key,</span> <span class="pre">default=None)</span></tt></p>
<p>Example: <tt class="docutils literal"><span class="pre">fav_color</span> <span class="pre">=</span> <span class="pre">request.session.get('fav_color',</span> <span class="pre">'red')</span></tt></p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">keys()</span></tt></p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">items()</span></tt></p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">setdefault()</span></tt></p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">clear()</span></tt></p>
</li>
</ul>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <tt class="docutils literal"><span class="pre">setdefault()</span></tt> and <tt class="docutils literal"><span class="pre">clear()</span></tt> are new in this version.</div>
<p>It also has these methods:</p>
<ul>
<li><p class="first"><tt class="docutils literal"><span class="pre">flush()</span></tt></p>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>Delete the current session data from the database and regenerate the
session key value that is sent back to the user in the cookie. This is
used if you want to ensure that the previous session data can’t be
accessed again from the user’s browser (for example, the
<a title="django.contrib.auth.logout" class="reference external" href="http://docs.djangoproject.com/en/1.0/topics/auth/#django.contrib.auth.logout"><tt class="xref docutils literal"><span class="pre">django.contrib.auth.logout()</span></tt></a> function calls it).</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">set_test_cookie()</span></tt></p>
<p>Sets a test cookie to determine whether the user’s browser supports
cookies. Due to the way cookies work, you won’t be able to test this
until the user’s next page request. See <a class="reference internal" href="#setting-test-cookies">Setting test cookies</a> below for
more information.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">test_cookie_worked()</span></tt></p>
<p>Returns either <tt class="xref docutils literal"><span class="pre">True</span></tt> or <tt class="xref docutils literal"><span class="pre">False</span></tt>, depending on whether the user’s
browser accepted the test cookie. Due to the way cookies work, you’ll
have to call <tt class="docutils literal"><span class="pre">set_test_cookie()</span></tt> on a previous, separate page request.
See <a class="reference internal" href="#setting-test-cookies">Setting test cookies</a> below for more information.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">delete_test_cookie()</span></tt></p>
<p>Deletes the test cookie. Use this to clean up after yourself.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">set_expiry(value)</span></tt></p>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>Sets the expiration time for the session. You can pass a number of
different values:</p>
<ul class="simple">
<li>If <tt class="docutils literal"><span class="pre">value</span></tt> is an integer, the session will expire after that
many seconds of inactivity. For example, calling
<tt class="docutils literal"><span class="pre">request.session.set_expiry(300)</span></tt> would make the session expire
in 5 minutes.</li>
<li>If <tt class="docutils literal"><span class="pre">value</span></tt> is a <tt class="docutils literal"><span class="pre">datetime</span></tt> or <tt class="docutils literal"><span class="pre">timedelta</span></tt> object, the
session will expire at that specific date/time.</li>
<li>If <tt class="docutils literal"><span class="pre">value</span></tt> is <tt class="docutils literal"><span class="pre">0</span></tt>, the user’s session cookie will expire
when the user’s Web browser is closed.</li>
<li>If <tt class="docutils literal"><span class="pre">value</span></tt> is <tt class="xref docutils literal"><span class="pre">None</span></tt>, the session reverts to using the global
session expiry policy.</li>
</ul>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">get_expiry_age()</span></tt></p>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>Returns the number of seconds until this session expires. For sessions
with no custom expiration (or those set to expire at browser close), this
will equal <tt class="docutils literal"><span class="pre">settings.SESSION_COOKIE_AGE</span></tt>.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">get_expiry_date()</span></tt></p>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>Returns the date this session will expire. For sessions with no custom
expiration (or those set to expire at browser close), this will equal the
date <tt class="docutils literal"><span class="pre">settings.SESSION_COOKIE_AGE</span></tt> seconds from now.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">get_expire_at_browser_close()</span></tt></p>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>Returns either <tt class="xref docutils literal"><span class="pre">True</span></tt> or <tt class="xref docutils literal"><span class="pre">False</span></tt>, depending on whether the user’s
session cookie will expire when the user’s Web browser is closed.</p>
</li>
</ul>
<p>You can edit <tt class="docutils literal"><span class="pre">request.session</span></tt> at any point in your view. You can edit it
multiple times.</p>
<div class="section" id="s-session-object-guidelines">
<span id="session-object-guidelines"></span><h3>Session object guidelines<a class="headerlink" href="#session-object-guidelines" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li>Use normal Python strings as dictionary keys on <tt class="docutils literal"><span class="pre">request.session</span></tt>. This
is more of a convention than a hard-and-fast rule.</li>
<li>Session dictionary keys that begin with an underscore are reserved for
internal use by Django.</li>
<li>Don’t override <tt class="docutils literal"><span class="pre">request.session</span></tt> with a new object, and don’t access or
set its attributes. Use it like a Python dictionary.</li>
</ul>
</div>
<div class="section" id="s-examples">
<span id="examples"></span><h3>Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h3>
<p>This simplistic view sets a <tt class="docutils literal"><span class="pre">has_commented</span></tt> variable to <tt class="xref docutils literal"><span class="pre">True</span></tt> after a user
posts a comment. It doesn’t let a user post a comment more than once:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">post_comment</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">new_comment</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'has_commented'</span><span class="p">,</span> <span class="bp">False</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s">"You've already commented."</span><span class="p">)</span>
    <span class="n">c</span> <span class="o">=</span> <span class="n">comments</span><span class="o">.</span><span class="n">Comment</span><span class="p">(</span><span class="n">comment</span><span class="o">=</span><span class="n">new_comment</span><span class="p">)</span>
    <span class="n">c</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
    <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s">'has_commented'</span><span class="p">]</span> <span class="o">=</span> <span class="bp">True</span>
    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s">'Thanks for your comment!'</span><span class="p">)</span>
</pre></div>
</div>
<p>This simplistic view logs in a "member" of the site:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">login</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">m</span> <span class="o">=</span> <span class="n">Member</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="n">request</span><span class="o">.</span><span class="n">POST</span><span class="p">[</span><span class="s">'username'</span><span class="p">])</span>
    <span class="k">if</span> <span class="n">m</span><span class="o">.</span><span class="n">password</span> <span class="o">==</span> <span class="n">request</span><span class="o">.</span><span class="n">POST</span><span class="p">[</span><span class="s">'password'</span><span class="p">]:</span>
        <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s">'member_id'</span><span class="p">]</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">id</span>
        <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s">"You're logged in."</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s">"Your username and password didn't match."</span><span class="p">)</span>
</pre></div>
</div>
<p>...And this one logs a member out, according to <tt class="docutils literal"><span class="pre">login()</span></tt> above:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">logout</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">del</span> <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s">'member_id'</span><span class="p">]</span>
    <span class="k">except</span> <span class="ne">KeyError</span><span class="p">:</span>
        <span class="k">pass</span>
    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s">"You're logged out."</span><span class="p">)</span>
</pre></div>
</div>
<p>The standard <tt class="docutils literal"><span class="pre">django.contrib.auth.logout()</span></tt> function actually does a bit
more than this to prevent inadvertent data leakage. It calls
<tt class="docutils literal"><span class="pre">request.session.flush()</span></tt>. We are using this example as a demonstration of
how to work with session objects, not as a full <tt class="docutils literal"><span class="pre">logout()</span></tt> implementation.</p>
</div>
</div>
<div class="section" id="s-setting-test-cookies">
<span id="setting-test-cookies"></span><h2>Setting test cookies<a class="headerlink" href="#setting-test-cookies" title="Permalink to this headline">¶</a></h2>
<p>As a convenience, Django provides an easy way to test whether the user's
browser accepts cookies. Just call <tt class="docutils literal"><span class="pre">request.session.set_test_cookie()</span></tt> in a
view, and call <tt class="docutils literal"><span class="pre">request.session.test_cookie_worked()</span></tt> in a subsequent view --
not in the same view call.</p>
<p>This awkward split between <tt class="docutils literal"><span class="pre">set_test_cookie()</span></tt> and <tt class="docutils literal"><span class="pre">test_cookie_worked()</span></tt>
is necessary due to the way cookies work. When you set a cookie, you can't
actually tell whether a browser accepted it until the browser's next request.</p>
<p>It's good practice to use <tt class="docutils literal"><span class="pre">delete_test_cookie()</span></tt> to clean up after yourself.
Do this after you've verified that the test cookie worked.</p>
<p>Here's a typical usage example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">login</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">method</span> <span class="o">==</span> <span class="s">'POST'</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">test_cookie_worked</span><span class="p">():</span>
            <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">delete_test_cookie</span><span class="p">()</span>
            <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s">"You're logged in."</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s">"Please enable cookies and try again."</span><span class="p">)</span>
    <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">set_test_cookie</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">render_to_response</span><span class="p">(</span><span class="s">'foo/login_form.html'</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-using-sessions-out-of-views">
<span id="using-sessions-out-of-views"></span><h2>Using sessions out of views<a class="headerlink" href="#using-sessions-out-of-views" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>An API is available to manipulate session data outside of a view:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">from</span> <span class="nn">django.contrib.sessions.backends.db</span> <span class="k">import</span> <span class="n">SessionStore</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">SessionStore</span><span class="p">(</span><span class="n">session_key</span><span class="o">=</span><span class="s">'2b1189a188b44ad18c35e113ac6ceead'</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="p">[</span><span class="s">'last_login'</span><span class="p">]</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="p">(</span><span class="mf">2005</span><span class="p">,</span> <span class="mf">8</span><span class="p">,</span> <span class="mf">20</span><span class="p">,</span> <span class="mf">13</span><span class="p">,</span> <span class="mf">35</span><span class="p">,</span> <span class="mf">10</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="p">[</span><span class="s">'last_login'</span><span class="p">]</span>
<span class="go">datetime.datetime(2005, 8, 20, 13, 35, 0)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>If you're using the <tt class="docutils literal"><span class="pre">django.contrib.sessions.backends.db</span></tt> backend, each
session is just a normal Django model. The <tt class="docutils literal"><span class="pre">Session</span></tt> model is defined in
<tt class="docutils literal"><span class="pre">django/contrib/sessions/models.py</span></tt>. Because it's a normal model, you can
access sessions using the normal Django database API:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">from</span> <span class="nn">django.contrib.sessions.models</span> <span class="k">import</span> <span class="n">Session</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">Session</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="s">'2b1189a188b44ad18c35e113ac6ceead'</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">expire_date</span>
<span class="go">datetime.datetime(2005, 8, 20, 13, 35, 12)</span>
</pre></div>
</div>
<p>Note that you'll need to call <tt class="docutils literal"><span class="pre">get_decoded()</span></tt> to get the session dictionary.
This is necessary because the dictionary is stored in an encoded format:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">session_data</span>
<span class="go">'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">get_decoded</span><span class="p">()</span>
<span class="go">{'user_id': 42}</span>
</pre></div>
</div>
</div>
<div class="section" id="s-when-sessions-are-saved">
<span id="when-sessions-are-saved"></span><h2>When sessions are saved<a class="headerlink" href="#when-sessions-are-saved" title="Permalink to this headline">¶</a></h2>
<p>By default, Django only saves to the session database when the session has been
modified -- that is if any of its dictionary values have been assigned or
deleted:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Session is modified.</span>
<span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s">'foo'</span><span class="p">]</span> <span class="o">=</span> <span class="s">'bar'</span>

<span class="c"># Session is modified.</span>
<span class="k">del</span> <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s">'foo'</span><span class="p">]</span>

<span class="c"># Session is modified.</span>
<span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s">'foo'</span><span class="p">]</span> <span class="o">=</span> <span class="p">{}</span>

<span class="c"># Gotcha: Session is NOT modified, because this alters</span>
<span class="c"># request.session['foo'] instead of request.session.</span>
<span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s">'foo'</span><span class="p">][</span><span class="s">'bar'</span><span class="p">]</span> <span class="o">=</span> <span class="s">'baz'</span>
</pre></div>
</div>
<p>In the last case of the above example, we can tell the session object
explicitly that it has been modified by setting the <tt class="docutils literal"><span class="pre">modified</span></tt> attribute on
the session object:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">modified</span> <span class="o">=</span> <span class="bp">True</span>
</pre></div>
</div>
<p>To change this default behavior, set the <tt class="docutils literal"><span class="pre">SESSION_SAVE_EVERY_REQUEST</span></tt> setting
to <tt class="xref docutils literal"><span class="pre">True</span></tt>. If <tt class="docutils literal"><span class="pre">SESSION_SAVE_EVERY_REQUEST</span></tt> is <tt class="xref docutils literal"><span class="pre">True</span></tt>, Django will save
the session to the database on every single request.</p>
<p>Note that the session cookie is only sent when a session has been created or
modified. If <tt class="docutils literal"><span class="pre">SESSION_SAVE_EVERY_REQUEST</span></tt> is <tt class="xref docutils literal"><span class="pre">True</span></tt>, the session cookie
will be sent on every request.</p>
<p>Similarly, the <tt class="docutils literal"><span class="pre">expires</span></tt> part of a session cookie is updated each time the
session cookie is sent.</p>
</div>
<div class="section" id="s-browser-length-sessions-vs-persistent-sessions">
<span id="browser-length-sessions-vs-persistent-sessions"></span><h2>Browser-length sessions vs. persistent sessions<a class="headerlink" href="#browser-length-sessions-vs-persistent-sessions" title="Permalink to this headline">¶</a></h2>
<p>You can control whether the session framework uses browser-length sessions vs.
persistent sessions with the <tt class="docutils literal"><span class="pre">SESSION_EXPIRE_AT_BROWSER_CLOSE</span></tt> setting.</p>
<p>By default, <tt class="docutils literal"><span class="pre">SESSION_EXPIRE_AT_BROWSER_CLOSE</span></tt> is set to <tt class="xref docutils literal"><span class="pre">False</span></tt>, which
means session cookies will be stored in users' browsers for as long as
<tt class="docutils literal"><span class="pre">SESSION_COOKIE_AGE</span></tt>. Use this if you don't want people to have to log in
every time they open a browser.</p>
<p>If <tt class="docutils literal"><span class="pre">SESSION_EXPIRE_AT_BROWSER_CLOSE</span></tt> is set to <tt class="xref docutils literal"><span class="pre">True</span></tt>, Django will use
browser-length cookies -- cookies that expire as soon as the user closes his or
her browser. Use this if you want people to have to log in every time they open
a browser.</p>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>This setting is a global default and can be overwritten at a per-session level
by explicitly calling <tt class="docutils literal"><span class="pre">request.session.set_expiry()</span></tt> as described above in
<a class="reference internal" href="#using-sessions-in-views">using sessions in views</a>.</p>
</div>
<div class="section" id="s-clearing-the-session-table">
<span id="clearing-the-session-table"></span><h2>Clearing the session table<a class="headerlink" href="#clearing-the-session-table" title="Permalink to this headline">¶</a></h2>
<p>Note that session data can accumulate in the <tt class="docutils literal"><span class="pre">django_session</span></tt> database table
and Django does <em>not</em> provide automatic purging. Therefore, it's your job to
purge expired sessions on a regular basis.</p>
<p>To understand this problem, consider what happens when a user uses a session.
When a user logs in, Django adds a row to the <tt class="docutils literal"><span class="pre">django_session</span></tt> database
table. Django updates this row each time the session data changes. If the user
logs out manually, Django deletes the row. But if the user does <em>not</em> log out,
the row never gets deleted.</p>
<p>Django provides a sample clean-up script in <tt class="docutils literal"><span class="pre">django-admin.py</span> <span class="pre">cleanup</span></tt>.
That script deletes any session in the session table whose <tt class="docutils literal"><span class="pre">expire_date</span></tt> is
in the past -- but your application may have different requirements.</p>
</div>
<div class="section" id="s-settings">
<span id="settings"></span><h2>Settings<a class="headerlink" href="#settings" title="Permalink to this headline">¶</a></h2>
<p>A few <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#ref-settings"><em>Django settings</em></a> give you control over session behavior:</p>
<div class="section" id="s-session-engine">
<span id="session-engine"></span><h3>SESSION_ENGINE<a class="headerlink" href="#session-engine" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>Default: <tt class="docutils literal"><span class="pre">django.contrib.sessions.backends.db</span></tt></p>
<p>Controls where Django stores session data. Valid values are:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">'django.contrib.sessions.backends.db'</span></tt></li>
<li><tt class="docutils literal"><span class="pre">'django.contrib.sessions.backends.file'</span></tt></li>
<li><tt class="docutils literal"><span class="pre">'django.contrib.sessions.backends.cache'</span></tt></li>
</ul>
<p>See <a class="reference internal" href="#configuring-the-session-engine">configuring the session engine</a> for more details.</p>
</div>
<div class="section" id="s-session-file-path">
<span id="session-file-path"></span><h3>SESSION_FILE_PATH<a class="headerlink" href="#session-file-path" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>Default: <tt class="docutils literal"><span class="pre">/tmp/</span></tt></p>
<p>If you're using file-based session storage, this sets the directory in
which Django will store session data.</p>
</div>
<div class="section" id="s-session-cookie-age">
<span id="session-cookie-age"></span><h3>SESSION_COOKIE_AGE<a class="headerlink" href="#session-cookie-age" title="Permalink to this headline">¶</a></h3>
<p>Default: <tt class="docutils literal"><span class="pre">1209600</span></tt> (2 weeks, in seconds)</p>
<p>The age of session cookies, in seconds.</p>
</div>
<div class="section" id="s-session-cookie-domain">
<span id="session-cookie-domain"></span><h3>SESSION_COOKIE_DOMAIN<a class="headerlink" href="#session-cookie-domain" title="Permalink to this headline">¶</a></h3>
<p>Default: <tt class="xref docutils literal"><span class="pre">None</span></tt></p>
<p>The domain to use for session cookies. Set this to a string such as
<tt class="docutils literal"><span class="pre">".lawrence.com"</span></tt> for cross-domain cookies, or use <tt class="xref docutils literal"><span class="pre">None</span></tt> for a standard
domain cookie.</p>
</div>
<div class="section" id="s-session-cookie-name">
<span id="session-cookie-name"></span><h3>SESSION_COOKIE_NAME<a class="headerlink" href="#session-cookie-name" title="Permalink to this headline">¶</a></h3>
<p>Default: <tt class="docutils literal"><span class="pre">'sessionid'</span></tt></p>
<p>The name of the cookie to use for sessions. This can be whatever you want.</p>
</div>
<div class="section" id="s-session-cookie-secure">
<span id="session-cookie-secure"></span><h3>SESSION_COOKIE_SECURE<a class="headerlink" href="#session-cookie-secure" title="Permalink to this headline">¶</a></h3>
<p>Default: <tt class="xref docutils literal"><span class="pre">False</span></tt></p>
<p>Whether to use a secure cookie for the session cookie. If this is set to
<tt class="xref docutils literal"><span class="pre">True</span></tt>, the cookie will be marked as "secure," which means browsers may
ensure that the cookie is only sent under an HTTPS connection.</p>
</div>
<div class="section" id="s-session-expire-at-browser-close">
<span id="session-expire-at-browser-close"></span><h3>SESSION_EXPIRE_AT_BROWSER_CLOSE<a class="headerlink" href="#session-expire-at-browser-close" title="Permalink to this headline">¶</a></h3>
<p>Default: <tt class="xref docutils literal"><span class="pre">False</span></tt></p>
<p>Whether to expire the session when the user closes his or her browser. See
"Browser-length sessions vs. persistent sessions" above.</p>
</div>
<div class="section" id="s-session-save-every-request">
<span id="session-save-every-request"></span><h3>SESSION_SAVE_EVERY_REQUEST<a class="headerlink" href="#session-save-every-request" title="Permalink to this headline">¶</a></h3>
<p>Default: <tt class="xref docutils literal"><span class="pre">False</span></tt></p>
<p>Whether to save the session data on every request. If this is <tt class="xref docutils literal"><span class="pre">False</span></tt>
(default), then the session data will only be saved if it has been modified --
that is, if any of its dictionary values have been assigned or deleted.</p>
</div>
</div>
<div class="section" id="s-technical-details">
<span id="technical-details"></span><h2>Technical details<a class="headerlink" href="#technical-details" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li>The session dictionary should accept any pickleable Python object. See
<a class="reference external" href="http://docs.python.org/library/pickle.html">the pickle module</a> for more information.</li>
<li>Session data is stored in a database table named <tt class="docutils literal"><span class="pre">django_session</span></tt> .</li>
<li>Django only sends a cookie if it needs to. If you don't set any session
data, it won't send a session cookie.</li>
</ul>
</div>
<div class="section" id="s-session-ids-in-urls">
<span id="session-ids-in-urls"></span><h2>Session IDs in URLs<a class="headerlink" href="#session-ids-in-urls" title="Permalink to this headline">¶</a></h2>
<p>The Django sessions framework is entirely, and solely, cookie-based. It does
not fall back to putting session IDs in URLs as a last resort, as PHP does.
This is an intentional design decision. Not only does that behavior make URLs
ugly, it makes your site vulnerable to session-ID theft via the "Referer"
header.</p>
</div>
</div>



<div id="content-secondary">
  <h2 id="comments">Questions/Feedback</h2>
  <p>Having trouble? We'd like to help!</p>
  <ul>
    <li>
      Try the <a href="http://docs.djangoproject.com/en/dev/faq/">FAQ</a> — it's got answers to many common
      questions.
    </li>
    <li>
      Search for information in the <a href="http://groups.google.com/group/django-users/">archives of the
      django-users mailing list</a>, or <a href="http://groups.google.com/group/django-users/">post a question</a>.
    </li>
    <li>
      Ask a question in the <a href="irc://irc.freenode.net/">#django IRC
      channel</a>, or search the <a href="http://oebfare.com/logger/django/">IRC
      logs</a> to see if its been asked before.
    </li>
    <li>
      If you notice errors with this documentation, please <a href="http://code.djangoproject.com/simpleticket?component=Documentation">
      open a ticket</a> and let us know! Please only use the ticket tracker for
      criticisms and improvements on the docs. For tech support, use the
      resources above.
    </li>
  </ul>
</div>

		</div>
		<!-- END #content-main -->
		<div id="content-related" class="sidebar">
		
  
    <h2>Contents</h2>
    
      <ul>
<li><a class="reference external" href="">How to use sessions</a><ul>
<li><a class="reference external" href="#enabling-sessions">Enabling sessions</a></li>
<li><a class="reference external" href="#configuring-the-session-engine">Configuring the session engine</a><ul>
<li><a class="reference external" href="#using-file-based-sessions">Using file-based sessions</a></li>
<li><a class="reference external" href="#using-cache-based-sessions">Using cache-based sessions</a></li>
</ul>
</li>
<li><a class="reference external" href="#using-sessions-in-views">Using sessions in views</a><ul>
<li><a class="reference external" href="#session-object-guidelines">Session object guidelines</a></li>
<li><a class="reference external" href="#examples">Examples</a></li>
</ul>
</li>
<li><a class="reference external" href="#setting-test-cookies">Setting test cookies</a></li>
<li><a class="reference external" href="#using-sessions-out-of-views">Using sessions out of views</a></li>
<li><a class="reference external" href="#when-sessions-are-saved">When sessions are saved</a></li>
<li><a class="reference external" href="#browser-length-sessions-vs-persistent-sessions">Browser-length sessions vs. persistent sessions</a></li>
<li><a class="reference external" href="#clearing-the-session-table">Clearing the session table</a></li>
<li><a class="reference external" href="#settings">Settings</a><ul>
<li><a class="reference external" href="#session-engine">SESSION_ENGINE</a></li>
<li><a class="reference external" href="#session-file-path">SESSION_FILE_PATH</a></li>
<li><a class="reference external" href="#session-cookie-age">SESSION_COOKIE_AGE</a></li>
<li><a class="reference external" href="#session-cookie-domain">SESSION_COOKIE_DOMAIN</a></li>
<li><a class="reference external" href="#session-cookie-name">SESSION_COOKIE_NAME</a></li>
<li><a class="reference external" href="#session-cookie-secure">SESSION_COOKIE_SECURE</a></li>
<li><a class="reference external" href="#session-expire-at-browser-close">SESSION_EXPIRE_AT_BROWSER_CLOSE</a></li>
<li><a class="reference external" href="#session-save-every-request">SESSION_SAVE_EVERY_REQUEST</a></li>
</ul>
</li>
<li><a class="reference external" href="#technical-details">Technical details</a></li>
<li><a class="reference external" href="#session-ids-in-urls">Session IDs in URLs</a></li>
</ul>
</li>
</ul>

    
  
  
  
    <h2>Search</h2>
    
    <form action="/en/1.0/search/" id="search" class="search">
  <div>
    <input name="cx" value="009763561546736975936:e88ek0eurf4" type="hidden">
    <input name="cof" value="FORID:11" type="hidden">
    <input name="ie" value="UTF-8" type="hidden">
    <input name="hl" value="" type="hidden">
    <input style="background: rgb(255, 255, 255) url(http://www.google.com/coop/intl/en/images/google_custom_search_watermark.gif) no-repeat scroll left center; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" id="id_search_q" class="query" name="q" type="text">
    <input name="sa" class="submit" value="Search" type="submit">
    <ul>
<li><label for="id_search_as_q_0"><input checked="checked" id="id_search_as_q_0" value="more:dev_docs" name="as_q" type="radio"> Latest</label></li>
<li><label for="id_search_as_q_1"><input id="id_search_as_q_1" value="more:1.0_docs" name="as_q" type="radio"> 1.0</label></li>
<li><label for="id_search_as_q_2"><input id="id_search_as_q_2" value="more:0.96_docs" name="as_q" type="radio"> 0.96</label></li>
<li><label for="id_search_as_q_3"><input id="id_search_as_q_3" value="more:all_docs" name="as_q" type="radio"> All</label></li>
</ul>
  </div>
</form>
<script type="text/javascript" src="Django%20%7C%20How%20to%20use%20sessions%20%7C%20Django%20Documentation_files/brand.html"></script>
  
  
  
    <h2>Browse</h2>
    <ul>
      
        
          <li>Prev: <a href="http://docs.djangoproject.com/en/1.0/topics/http/middleware/">Middleware</a></li>
        
        
          <li>Next: <a href="http://docs.djangoproject.com/en/1.0/topics/forms/">Working with forms</a></li>
        
        <li><a href="http://docs.djangoproject.com/en/1.0/contents/">Table of contents</a></li>
        
          <li><a href="http://docs.djangoproject.com/en/1.0/genindex/">General Index</a></li>
        
          <li><a href="http://docs.djangoproject.com/en/1.0/modindex/">Global Module Index</a></li>
        
      
    </ul>
  
  
  
    <h2>You are here:</h2>
    <ul>
      
        <li>
          <a href="http://docs.djangoproject.com/en/1.0/">Django 1.0 documentation</a>
          
            <ul><li><a href="http://docs.djangoproject.com/en/1.0/topics/">Using Django</a>
          
            <ul><li><a href="http://docs.djangoproject.com/en/1.0/topics/http/">Handling HTTP requests</a>
          
          <ul><li>How to use sessions</li></ul>
          </li></ul></li></ul>
        </li>
      
    </ul>
  
  
  
    <h3>Last update:</h3>
    <div>May 23, 2009, 8:15 a.m. (<a href="http://www.timeanddate.com/worldclock/city.html?n=64">CDT</a>)</div>
  

		</div>
		<!-- END #content-related -->

		</div>
		<!-- END #content -->
		<div id="footer">
			<p>© 2005-2009 <a href="http://www.djangoproject.com/foundation/">Django Software Foundation</a> unless otherwise noted. Django is a registered trademark of the Django Software Foundation. 
			Hosting graciously provided by <a href="http://mediatemple.net/">
			<img style="vertical-align: middle; position: relative; top: -1px;" src="Django%20%7C%20How%20to%20use%20sessions%20%7C%20Django%20Documentation_files/mt.png" alt="media temple"></a>
			</p>
		</div>
		<!-- END #footer -->
	</div>
	<!-- END #container -->
	</body></html>